<template>
  <el-dialog
    :before-close="handleClose"
    :title="status === 'Add' ? '新增商品' : '编辑商品'"
    :visible.sync="dialogVisible"
    width="50%"
  >
    <el-form
      ref="ruleForm"
      :model="ruleForm"
      :rules="rules"
      class="demo-ruleForm"
      label-width="180px"
    >
      <el-form-item label="阶段等级" prop="grade">
        <el-input v-model="ruleForm.grade" placeholder="请输入类型" style="width: 60%;" type="number"></el-input>
      </el-form-item>
      <el-form-item label="等级阶段名称" prop="name">
        <el-input v-model="ruleForm.name" placeholder="请输入特权名称" style="width: 60%;"></el-input>
      </el-form-item>
      <el-form-item label="等级特权" prop="privilegeArr">
        <el-select v-model="ruleForm.privilegeArr" multiple placeholder="请选择">
          <el-option
            v-for="item in privilegeArr"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="展示大图" prop="big_img">
        <el-upload

          :http-request="customizeUpload"
          :on-success="handleSuccess"
          :show-file-list="false"
          action=""
          class="avatar-uploader"
        >
          <img v-if="ruleForm.big_img" :src="ruleForm.big_img" class="avatar"/>
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button
        :loading="submitLoading"
        type="primary"
        @click="submitForm('ruleForm')"
      >提交</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getList, privilegeAdd, privilegeEdit } from '@/api/dailyCheck/vipLevelManagement'

export default {
  name: 'indexAddEdit',
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    // 模态框的状态 Add 为新增  Edit为编辑
    status: {
      type: String,
      default: ['Add']
    },
    detail: {
      type: Object,
      default: {}
    }
  },
  data() {
    return {
      submitLoading: false,
      privilegeArr: [],
      ruleForm: {
        grade: null, // 等级，必传
        name: null, //等级名称，必传
        big_img: null, // 展示大图，必传
        privilegeArr: [],
        privilege_id: null  // 等级特权id json示例格式[1,2,3]，必传
      },

      rules: {
        grade: [{ required: true, message: '请输入阶段等级', trigger: 'blur' }],
        name: [{ required: true, message: '请输入等级阶段名称', trigger: 'blur' }],
        big_img: [{ required: true, message: '请上传展示大图', trigger: 'blur' }],
        privilegeArr: [{ required: true, message: '请选择等级特权', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    async getList() {
      const { data } = await getList()
      this.privilegeArr = data
    },
    handleClose(done) {
      this.$emit('update:dialogVisible', false)
      for (const detailKey in this.ruleForm) {
        this.ruleForm[detailKey] = null
      }
      this.resetForm('ruleForm')
      this.$emit('update:status', 'Add')
      this.$emit('update:detail', {})
    },
    submitForm(formName) {
      let data = {}
      for (const dataKey in this.ruleForm) {
        if (
          dataKey !== 'checkedCities' ||
          !(
            !this.ruleForm[dataKey] &&
            typeof this.ruleForm[dataKey] != 'undefined' &&
            this.ruleForm[dataKey] != 0
          )
        ) {
          data[dataKey] = this.ruleForm[dataKey]
        }
        // 过滤掉为 null
      }
      data.privilege_id = JSON.stringify(this.ruleForm.privilegeArr)
      this.$refs[formName].validate(async valid => {
        if (!valid) {
          this.submitLoading = false
          return false
        }
        this.submitLoading = true
        let detail
        // 新增活动商品
        if (this.status === 'Add') {
          detail = await privilegeAdd(data)
        } else {
          // 编辑
          detail = await privilegeEdit(data)
        }
        if (detail.code === 200) {
          this.$message.success(this.status === 'Add' ? '添加成功!' : '编辑成功')
          this.$emit('update:dialogVisible', false)
          this.$emit('updateTable')
          for (const detailKey in this.ruleForm) {
            this.ruleForm[detailKey] = null
          }
          this.$emit('update:status', 'Add')
        }
        this.submitLoading = false
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    handleSuccess() {
      this.ruleForm.big_img = this.ossLastImgUrl
    }
  },
  watch: {
    async status(newVal) {
      /* 当 status 为 Edit 则 为编辑框, 需要完成数据的回显   */
      if (newVal == 'Edit') {
        this.ruleForm = Object.assign({}, this.detail)
        console.log(this.detail)
        this.ruleForm.privilegeArr = []
        this.detail.privilege_data.map(item => this.ruleForm.privilegeArr.push(item.id))
      } else {
        for (const detailKey in this.ruleForm) {
          this.ruleForm[detailKey] = null
        }
      }
    }
  }
}
</script>

<style scoped>
::v-deep.avatar-uploader .el-upload {
  border        : 1px dashed #d9d9d9;
  border-radius : 6px;
  cursor        : pointer;
  position      : relative;
  overflow      : hidden;
}

.avatar-uploader .el-upload:hover {
  border-color : #409eff;
}

.avatar-uploader-icon {
  font-size   : 28px;
  color       : #8c939d;
  width       : 100px;
  height      : 100px;
  line-height : 100px;
  text-align  : center;
}

.avatar {
  width   : 100px;
  height  : 100px;
  display : block;
}

::v-deep .lu-input {
  width : 300px !important;
}

</style>
